/*
 * @Author: wangtao
 * @Date: 2020-08-20 14:07:42
 * @LastEditors: kanglang
 * @LastEditTime: 2021-04-28 18:55:03
 * @Description: 货主端首页 运力地图
 */

import React from 'react';
import {
  View,
  StyleSheet,
  Image,
  Text,
  SafeAreaView,
  TouchableOpacity,
  NativeModules,
  Platform,
  NativeEventEmitter,
  DeviceEventEmitter,
  BackHandler,
} from 'react-native';
import LinearGradient from 'react-native-linear-gradient';
import { iconWlHome, iconWlHomeGray, position } from '../../../../image';
import { BackImage, msg, Header } from '../../../../common';
import { isAndroid, mainBgColorLightGray, px2dp } from '../../../../common/styles';
import MapView from '../../../../components/MapView';
import Picker from '../../../../common/picker';
import supply from '../../../../api/supply';
import user from '../../../../api/user';

export default class CapacityMap extends React.Component {
  static navigationOptions = () => ({
    title: '首页',
    tabBarIcon: ({ focused }) => (
      <Image
        source={focused ? iconWlHome : iconWlHomeGray}
        style={{ width: 24, height: 24 }}
      />
    ),
  });

  constructor(props) {
    super(props);
    this.state = {
      driverNum: 0,

      /* 选择当前用户类型 */
      consignorType: 0, // 货主类型
      custId: '', // 货主ID//个人取个人ID
      custType: 1, // 客户类型
      custIdDataList: [], // 货主ID列表
      custName: '', // 公司名字，个人传个人名字
      consignorTypeDataList: [], // 货主类型列表
      shouldShowData: false, // 是否获取到用户的类型
      /* end */
    };
  }

  componentDidMount() {
    // 处理安卓物理返回键
    if (Platform.OS == 'android') {
      BackHandler.addEventListener('hardwareBackPress', this.onBackAndroid);
    }

    // 首先通过接口获取状态，然后决定picker弹窗

    this.refs.mapView.nativeMethod('onCreate');
    this.refs.mapView.nativeMethod('startLocation');

    if (isAndroid) {
      this.methodOfListenerAndroid();
    } else {
      this.methodOfListenerIOS();
    }

    this.queryUserType();
  }

  componentWillUnmount() {
    this.listener.remove();
    this.zoomListener.remove();
    this.refs.mapView.nativeMethod('onDestroy');
    if (Platform.OS === 'android') {
      BackHandler.removeEventListener('hardwareBackPress', this.onBackAndroid);
    }
  }

  onBackAndroid = () => {
    Picker.hide();
    msg.emit('router: back');
    return true;
  };

  /** *******选择用户类型 start********** */
  // 查询用户状态
  queryUserType = () => {
    supply.saveOrGetConsignorRedis({}).then(res => {
      if (res.success) {
        if (res.data === null) {
          this.queryGetCustomLegals();
        } else {
          if (!res.data.custType || !res.data.custId || !res.data.consignorType) {
            this.queryGetCustomLegals();
          } else {
            this.setState({ shouldShowData: true });
            // 查询列表数据
            //   InteractionManager.runAfterInteractions(() => {
            //   this.loadData();
            // });
          }
        }
      } else {
        // 返回
        msg.emit('app:tip', { text: '获取用户信息失败' });
        setTimeout(() => {
          msg.emit('router: back');
        }, 1500);
      }
    });
  }

  // 上传用户状态
  updateUserType = () => {
    const { consignorType, custId, custType, custName } = this.state;
    supply.saveOrGetConsignorRedis({
      consignorType: consignorType,
      custId: custId,
      custType: custType,
      custName: custName
    }).then(res => {
      if (res.success) {
        this.setState({ shouldShowData: true });
        // 查询列表数据
        // InteractionManager.runAfterInteractions(() => {
        //   this.loadData();
        // });
      } else {
        // 返回
        msg.emit('app:tip', { text: '获取用户信息失败' });
        setTimeout(() => {
          msg.emit('router: back');
        }, 1500);
      }
    });
  }

  // 查询用户公司列表
  queryGetCustomLegals = () => {
    supply.getCustomLegals().then(res => {
      if (res.success) {
        if (res.data === null) {
          // 个人用户
          this.setState({
            custType: 1,
          }, () => {
            this.getUserInfo();
          });
        } else {
          // 企业用户
          this.setState({
            custIdDataList: res.data
          });
          // 弹窗选择
          this.showPicker('选择客户类型', ['企业', '个人'], 'custType');
        }
      } else {

      }
    });
  }

  // 查询货主类型
  queryGetallConsignorType = () => {
    supply.allConsignorType().then(res => {
      if (res.success) {
        if (res.data != null) {
          this.setState({
            consignorTypeDataList: res.data
          });
          let listData = [];
          res.data.map((item) => {
            listData.push(item.name);
          });
          // 弹窗选择
          this.showPicker('货主类型', listData, 'consignorType');
        }
      } else {

      }
    });
  }

  // 查询用户信息
  getUserInfo = () => {
    user.getUserInfo().then(res => {
      if (res.success) {
        this.setState({
          custName: res.data.name,
          custId: res.data.custId
        });
        this.queryGetallConsignorType();
      } else {
        // 返回
        // msg.emit('app:tip', { text: "获取用户信息失败" });
        // setTimeout(() => {
        //   msg.emit('router: back');
        // }, 1500);
      }
    });
  }

  showPicker = (title, dataList, pickerType) => {
    const { custIdDataList, consignorTypeDataList } = this.state;
    Picker.init({
      pickerTitleText: title,
      pickerCancelBtnText: '取消',
      pickerConfirmBtnColor: [186, 145, 74, 1],
      pickerCancelBtnColor: [102, 101, 100, 1],
      pickerConfirmBtnText: '确定',
      selectedValue: [

      ],
      pickerBg: [255, 255, 255, 1],
      pickerToolBarBg: [255, 255, 255, 1],
      pickerFontColor: [186, 145, 74, 1],
      pickerRowHeight: 40,
      pickerData: dataList,
      onPickerConfirm: (pickedValue, pickedIndex) => {
        // 点击确定
        if (pickerType === 'consignorType') {
          consignorTypeDataList.map((item) => {
            if (pickedValue[0] === item.name) {
              this.setState({
                consignorType: item.code
              });
            }
          });
          this.updateUserType();
        } else if (pickerType === 'custId') {
          custIdDataList.map((item) => {
            if (item.custName === pickedValue[0]) {
              this.setState({
                custId: item.custId,
                custName: item.custName
              });
            }
          });

          this.queryGetallConsignorType();
        } else if (pickerType === 'custType') {
          if (pickedValue[0] === '个人') {
            this.setState({
              custType: 1,
            });
            this.getUserInfo();
          } else {
            this.setState({
              custType: 2
            });
            if (custIdDataList === null) {
              this.queryGetCustomLegals();
            } else {
              let listData = [];
              custIdDataList.map((item) => {
                listData.push(item.custName);
              });
              this.showPicker('选择企业', listData, 'custId');
            }
          }
        }
      },
      onPickerCancel: (pickedValue, pickedIndex) => {
        msg.emit('router: back');
      },
      onPickerSelect: (pickedValue, pickedIndex) => {

      },
    });
    Picker.show();
  };
  /** *******选择用户类型 end********** */

  // 定位当前位置
  positionCenter = () => {
    this.refs.mapView.nativeMethod('startLocation');
  }

  drawOverlay(icon, list) {
    this.refs.mapView.nativeMethod('drawOverlay', [{ icon: icon }, { list: list }]);
  }

  drawOverlayTotal(list) {
    this.refs.mapView.nativeMethod('drawOverlayTotal', [{ list: list }]);
  }

  drawLine(list) {
    this.refs.mapView.nativeMethod('drawLine', [{ list: list }]);
  }

  // 安卓定位回调监听
  methodOfListenerAndroid = () => {
    this.listener = DeviceEventEmitter.addListener('LOCATION_RESULT', (jsonStr) => {
      // let location = JSON.parse(jsonStr);
      // this.drawOverlay("map_position_icon", [{ lat: location.latitude, lon: location.longitude }]);
      this.queryNumberOfCar(jsonStr);
    });
    this.zoomListener = DeviceEventEmitter.addListener('MAP_ZOOM_LEVEL', (jsonStr) => {
      this.queryMapData(jsonStr);
    });
  };

  // ios定位回调监听
  methodOfListenerIOS = () => {
    const { GJCommonEmitter } = NativeModules;
    const commonEmmiter = new NativeEventEmitter(GJCommonEmitter);
    this.listener = commonEmmiter.addListener('LOCATION_RESULT', (jsonStr) => {
      this.queryNumberOfCar(jsonStr);
    });
    this.zoomListener = commonEmmiter.addListener('MAP_ZOOM_LEVEL', (jsonStr) => {
      this.queryMapData(jsonStr);
    });
  };

  queryNumberOfCar = (jsonStr) => {
    let location = JSON.parse(jsonStr);
    this.setState({ locationData: location }, () => {
      supply.nearCarCount({ longitude: Number(location.longitude), latitude: Number(location.latitude) }).then((res) => {
        if (res.success) {
          this.setState({ driverNum: res.data });
        }
      });
    });
  }

  queryMapData = (jsonStr) => {
    const resLocatonData = JSON.parse(jsonStr);
    if (!resLocatonData) {
      return;
    }
    supply.nearCarInfo({ longitude: Number(resLocatonData.longitude), latitude: Number(resLocatonData.latitude), zoomLevel: Number(resLocatonData.zoomLevel) }).then((res) => {
      if (res.success && res.data) {
        switch (Number(resLocatonData.zoomLevel)) {
        // 3全国 4、5展示省查全国 678 展示市 查全省
        case 3: case 4: case 5: case 6: case 7: case 8:
          {
            // 展示车辆数量信息

            const mapDataList = res.data.area.map((item) => {
              const point = JSON.parse(item.point);
              return { lon: point[0], lat: point[1], num: item.carCount, name: item.name };
            });
            if (mapDataList.length > 0) {
              this.drawOverlayTotal(mapDataList);
            }
          }
          break;
        case 9: case 10: case 11: case 12: case 13: case 14: case 15: case 16: case 17: case 18: case 19: case 20:
          {
            const mapDataList = res.data.car.map((item) => {
              const point = JSON.parse(item.point);
              return { lon: point[0], lat: point[1] };
            });
            // 区，市 //展示车辆位置信息
            if (mapDataList.length > 0) {
              this.drawOverlay('icon_map_car', mapDataList);
            }
          }
          break;
        default:
        {

        }
        }
      }
    });
  }

  render() {
    const { driverNum } = this.state;
    return (
      <SafeAreaView>
        <Header
          title='运力地图'
          renderLeft={() => {
            return (
              <TouchableOpacity
                activeOpacity={0.8}
                style={isAndroid ? { paddingVertical: px2dp(14), paddingHorizontal: px2dp(40) } :
                  { paddingVertical: px2dp(14), paddingRight: px2dp(40) }}
                onPress={() => {
                  msg.emit('router: back');
                }}
              >
                <BackImage />
              </TouchableOpacity>
            );
          }}
          renderRight={() => { }}
        />
        <View style={styles.container}>
          {/* 附近司机数量 */}
          <View style={styles.map_header}>
            <LinearGradient
              colors={['#E5B867', '#BB934B']}
              style={styles.map_header_circle}
              start={{ x: 0, y: 0 }}
              end={{ x: 1, y: 0 }}
            >
              <Image style={styles.map_header_image} source={require('../../../../image/wl/icon_broadcas.png')} />
            </LinearGradient>
            <Text style={styles.map_header_text}>
              附近有
              {' '}
              <Text style={styles.map_header_num}>{driverNum}</Text>
              {' '}
              位司机等待您发货
            </Text>
          </View>
          {/* 地图组建 */}
          <MapView
            ref='mapView'
            locationIcon='icon_position_export'
            style={{ width: '100%', height: '100%' }}
          />
          {/* 去发货 */}
          {/* <ReleaseSourceDot style={{ positon: 'absolute', bottom: px2dp(380),left:px2dp(303) }} /> */}
          {/* 定位当前位置 */}
          <TouchableOpacity
            style={styles.map_position}
            onPress={() => {
              this.positionCenter();
            }}
          >
            <Image style={styles.map_position_image} source={require('../../../../image/wl/icon_Positioning.png')} />
          </TouchableOpacity>
        </View>
      </SafeAreaView>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    height: '100%',
    width: '100%',
    backgroundColor: mainBgColorLightGray,
  },
  map_header: {
    width: px2dp(500),
    height: px2dp(72),
    backgroundColor: 'white',
    position: 'absolute',
    top: px2dp(32),
    left: px2dp(125),
    zIndex: 999,
    borderRadius: px2dp(41),
    alignItems: 'center',
    flexDirection: 'row',
    paddingLeft: px2dp(8)
  },
  map_header_text: {
    fontSize: px2dp(28),
    color: '#343332',
  },
  map_header_num: {
    fontSize: px2dp(28),
    color: '#BA914A'
  },
  map_header_circle: {
    width: px2dp(56),
    height: px2dp(56),
    borderRadius: px2dp(28),
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    marginRight: px2dp(20)
  },
  map_header_image: {
    width: px2dp(32),
    height: px2dp(32),
  },
  map_position: {
    width: px2dp(76),
    height: px2dp(76),
    backgroundColor: '#fff',
    borderRadius: px2dp(12),
    position: 'absolute',
    left: px2dp(32),
    bottom: px2dp(244),
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center'
  },
  map_position_image: {
    width: px2dp(40),
    height: px2dp(40),
  }
});
